import React, { useEffect, useState } from "react";
import { isUndefined } from "@ct0/functions";
import { createUseStyles } from "react-jss";
import classNames from "classnames";

interface InputProps {
  value?: string;
  type: "string" | "number";
  placeholder?: string;
  className?: string;
  onChange?: (value?: string | number) => void;
  onInput?: (value?: string | number) => void;
}

const useStyles = createUseStyles({
  input: {
    margin: "10px",
    padding: "3px 5px",
    width: "220px",
    borderRadius: "4px",
    border: "1px solid #D9D9D9",
    color: "#333",
    "&:focus-visible": {
      outline: 0,
    },
    "&::placeholder": {
      color: "#c5c5c5",
    },
  },
});

export default function Input({
  value: propsValue,
  type,
  placeholder,
  onChange,
  onInput,
  className,
}: InputProps) {
  const classes = useStyles();
  const [value, setValue] = useState(propsValue);

  useEffect(() => {
    setValue(propsValue);
  }, [propsValue]);

  const change = (value?: string) => {
    if (isUndefined(value)) return;
    if (type == "number") return parseFloat(value);
    return value;
  };

  const enter = () => {
    onChange?.(change(value));
  };

  const handler = (value?: string) => setValue(value?.trim());

  const handleInput = (e: React.FormEvent<HTMLInputElement>) => {
    if (onInput) {
      const value = e.currentTarget.value;
      handler(e.currentTarget.value);
      onInput(change(value));
    }
  };

  return (
    <input
      className={classNames(classes.input, className)}
      placeholder={placeholder}
      value={value || ""}
      type={type}
      onKeyDown={(e) => e.key == "Enter" && enter()}
      onChange={(e) => handler(e.target.value || undefined)}
      onInput={handleInput}
    />
  );
}
